<?php
/**
 * Wenda_Model_User
 *
 * @category   Wenda
 * @package    Wenda_Model_Table
 * @copyright  Copyright (c) 2010 Ricky Feng (http://www.ilife-project.com)
 * @license    http://www.ilife-project.com/license.txt New BSD License
 */
class Frontend_Model_User extends Custom_Model_Abstract
{
    /**
     * Find User by their id
     * @param int  $id
     * @return null|Wenda_Table_Row_User
     */
    public function findById($id)
    {
        return Wenda::getTable('User')->findById($id);
    }

    /**
     * Find User by their name
     * @param string $name
     * @param Wenda_Table_Row_User $ignore
     * @return null|Wenda_Table_Row_User
     */

    public function findByName($name, $ignore = null)
    {
        return Wenda::getTable('User')->findByName($name,$ignore);
    }

    /**
     * Find User by their email
     * @param string $email
     * @param Wenda_Table_Row_User $ignore
     * @return null|Wenda_Table_Row_User
     */
    public function findByEmail($email, $ignore = null)
    {
        return Wenda::getTable('User')->findByEmail($email,$ignore);
    }

    /**
     * Get all Users
     *
     * @param  boolean $paged Return paginator?
     * @param  array   $order The order fields
     * @return Zend_Db_Table_Rowset
     */
    public function getUsers($paged=false, $order=null)
    {
        return Wenda::getTable('User')->getAll($paged, $order);
    }

    /**
     * Register a new user
     * @param array $post
     * @return false|int
     */
    public function register($post)
    {
        $form = Wenda::getForm('userRegister');
        return $this->_save($form, $post, array('group_id' => 10));
    }

    /**
     * Update user data
     * @param array $post
     * @param string $validator
     * @return false|int
     */
    public function update($post, $validator = null)
    {
        if (null === $validator) {
            $validator = 'edit';
        }

        $form = Wenda::getForm('user' . ucfirst($validator));

        return $this->_save($form, $post);
    }

    /**
     * Save the data to db
     *
     * @param  Zend_Form $form The Validator
     * @param  array     $info The data
     * @param  array     $defaults Default values
     * @return false|int
     */
    protected function _save($form, $info, $defaults=array())
    {
        if (!$form->isValid($info)) {
            return false;
        }

        // get filtered values
        $data = $form->getValues();

        // password hashing
        if (array_key_exists('password', $data) && '' == $data['password']) {
            unset($data['password']);
        }

        // apply any defaults
        foreach ($defaults as $col => $value) {
            $data[$col] = $value;
        }

        $user = array_key_exists('userId',$data) ? $this->findById($data['userId']) : null;

        return Wenda::getTable('User')->saveRow($data, $user);
    }
}